from flask import Flask, request, jsonify
from flask_cors import CORS
import os
from werkzeug.utils import secure_filename
from datetime import datetime
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 配置
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'xls', 'xlsx', 'zip', 'rar'}

# 创建上传目录
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 最大16MB

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def get_file_size(file_path):
    """获取文件大小（字节）"""
    try:
        return os.path.getsize(file_path)
    except OSError:
        return 0

@app.route('/upload', methods=['POST'])
def upload_file():
    """处理文件上传"""
    try:
        # 检查是否有文件
        if 'file' not in request.files:
            return jsonify({'error': '没有文件被上传'}), 400
        
        file = request.files['file']
        
        # 检查文件是否为空
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        # 检查文件类型
        if not allowed_file(file.filename):
            return jsonify({'error': '不支持的文件类型'}), 400
        
        # 安全文件名
        filename = secure_filename(file.filename)
        
        # 生成唯一文件名（防止重名）
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        base_name, extension = os.path.splitext(filename)
        unique_filename = f"{base_name}_{timestamp}{extension}"
        
        # 保存文件
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
        file.save(file_path)
        
        # 获取文件信息
        file_size = get_file_size(file_path)
        
        logger.info(f"文件上传成功: {unique_filename} ({file_size} 字节)")
        
        return jsonify({
            'message': '文件上传成功',
            'filename': unique_filename,
            'original_filename': filename,
            'size': file_size,
            'path': file_path
        }), 200
        
    except Exception as e:
        logger.error(f"文件上传失败: {str(e)}")
        return jsonify({'error': f'上传失败: {str(e)}'}), 500

@app.route('/uploads/<filename>', methods=['GET'])
def uploaded_file(filename):
    """获取已上传的文件"""
    try:
        return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
    except FileNotFoundError:
        return jsonify({'error': '文件不存在'}), 404

@app.route('/list', methods=['GET'])
def list_files():
    """列出所有上传的文件"""
    try:
        files = []
        for filename in os.listdir(app.config['UPLOAD_FOLDER']):
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            if os.path.isfile(file_path):
                files.append({
                    'filename': filename,
                    'size': get_file_size(file_path),
                    'upload_time': datetime.fromtimestamp(os.path.getctime(file_path)).strftime('%Y-%m-%d %H:%M:%S')
                })
        
        return jsonify({'files': files}), 200
    except Exception as e:
        return jsonify({'error': f'获取文件列表失败: {str(e)}'}), 500

@app.route('/delete/<filename>', methods=['DELETE'])
def delete_file(filename):
    """删除文件"""
    try:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(filename))
        if os.path.exists(file_path):
            os.remove(file_path)
            logger.info(f"文件删除成功: {filename}")
            return jsonify({'message': '文件删除成功'}), 200
        else:
            return jsonify({'error': '文件不存在'}), 404
    except Exception as e:
        logger.error(f"文件删除失败: {str(e)}")
        return jsonify({'error': f'删除失败: {str(e)}'}), 500

@app.route('/', methods=['GET'])
def index():
    """返回上传页面"""
    return '''
    <!DOCTYPE html>
    <html>
    <head>
        <title>文件上传服务</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 50px; }
            .info { background: #f0f0f0; padding: 20px; border-radius: 5px; }
            .endpoint { background: #e8f4f8; padding: 10px; margin: 10px 0; border-radius: 3px; }
        </style>
    </head>
    <body>
        <h1>文件上传服务 API</h1>
        <div class="info">
            <h2>可用端点：</h2>
            <div class="endpoint">
                <strong>POST /upload</strong> - 上传文件
            </div>
            <div class="endpoint">
                <strong>GET /list</strong> - 列出所有文件
            </div>
            <div class="endpoint">
                <strong>GET /uploads/&lt;filename&gt;</strong> - 获取文件
            </div>
            <div class="endpoint">
                <strong>DELETE /delete/&lt;filename&gt;</strong> - 删除文件
            </div>
            <p>支持的文件类型：txt, pdf, png, jpg, jpeg, gif, doc, docx, xls, xlsx, zip, rar</p>
            <p>最大文件大小：16MB</p>
        </div>
    </body>
    </html>
    '''

@app.errorhandler(413)
def too_large(e):
    """处理文件过大的错误"""
    return jsonify({'error': '文件过大，最大支持16MB'}), 413

@app.errorhandler(500)
def server_error(e):
    """处理服务器错误"""
    return jsonify({'error': '服务器内部错误'}), 500

if __name__ == '__main__':
    print("文件上传服务启动中...")
    print("访问 http://localhost:5000 查看API文档")
    print("支持的文件类型：", ", ".join(ALLOWED_EXTENSIONS))
    print("上传目录：", os.path.abspath(UPLOAD_FOLDER))
    
    app.run(debug=True, host='0.0.0.0', port=5000)